/*
 * FileName：AddressUtils.java
 * <p>
 * Copyright (c) 2017-2020 <a href="">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koine.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取地址类
 *
 * @author ruoyi
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String bdUrl = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=%s&co=&resource_id=6006&t=1433922612109&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110206955700272228569_1433922418817&_=1433922418822";
    //暂时废弃
//    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php?ip=%s";

    //    public static final String IP_URL = "https://tool.lu/ip/ajax.html?ip=%s";
    public static final String IP_BAIDU_URL = "https://api.map.baidu.com/location/ip?ip=%s&ak=%s";

    public static String getRealAddressByIP(String ip) {
        String address = "XX";

        // 内网不查询
        if (RequestUtil.internalIp(ip)) {
            return "内网IP";
        }
        String rspStr = HttpClientUtils.sendHttpGet(String.format(bdUrl, ip));
        if (StringUtil.isEmpty(rspStr)) {
            log.error("获取地理位置异常 {}", ip);
            return address;
        }
        //处理内容
        Matcher mat = Pattern.compile("(?<=\\()[^\\)]+").matcher(rspStr);
        while (mat.find()) {
            JSONObject jsonObject = JSONObject.parseObject(mat.group());
            JSONArray data = jsonObject.getJSONArray("data");
            return data.getJSONObject(0).getString("location");
        }
        return address;
    }

//    public static String getRealAddressCityByIP(String ip) {
//        String address = "XX";
//
//        // 内网不查询
//        if (RequestUtil.internalIp(ip)) {
//            return "内网IP";
//        }
//        Map<String, String> headers = Maps.newHashMap();
//        headers.put("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
//        headers.put("connection", "Keep-Alive");
//        headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
//        headers.put("Upgrade-Insecure-Requests", "1");
//        String rspStr = HttpClientUtils.sendHttpHeaderGet(String.format(IP_URL, ip), headers);
//        if (StringUtil.isEmpty(rspStr)) {
//            log.error("获取地理位置异常 {}", ip);
//            return address;
//        }
//        //处理内容
//        JSONObject jsonObject = JSONObject.parseObject(rspStr);
//        if (null != jsonObject && "0".equals(jsonObject.getString("code"))) {
//            return jsonObject.getJSONObject("data").getString("city");
//        }
//        return address;
//    }

    //public static String getRealAddressCityByIP(String ip) {
//    String address = "XX";
//
//    // 内网不查询
//    if (RequestUtil.internalIp(ip)) {
//        return "内网IP";
//    }
//    String rspStr = HttpClientUtils.sendHttpPost(String.format(IP_URL, ip));
//    if (StringUtil.isEmpty(rspStr)) {
//        log.error("获取地理位置异常 {}", ip);
//        return address;
//    }
//    //处理内容
//    JSONObject jsonObject = JSONObject.parseObject(rspStr);
//    if (null != jsonObject && "true".equals(jsonObject.getString("status"))) {
//        return jsonObject.getJSONObject("text").getString("ipip_location").split(" ")[2];
//    }
//    return address;
//}

    public static String getRealAddressCityByIP(String ip) {
        String address = "XX";

        // 内网不查询
        if (RequestUtil.internalIp(ip)) {
            return "内网IP";
        }
        String rspStr = HttpClientUtils.sendHttpPost(String.format(IP_BAIDU_URL, ip,PropertiesUtil.getString("baidu.ak")));
        if (StringUtil.isEmpty(rspStr)) {
            log.error("获取地理位置异常 {}", ip);
            return address;
        }
        //处理内容
        JSONObject jsonObject = JSONObject.parseObject(rspStr);
        if (null != jsonObject && "0".equals(jsonObject.getString("status"))) {
            String[] addresses = jsonObject.getString("address").split("\\|");
            return addresses[2];
        }
        return address;
    }
    public static void main(String[] args){
        System.out.println(AddressUtils.getRealAddressCityByIP("221.127.71.97"));
    }
}
